package com.ebupt.migu.fineoperationactivitymonitor.common.sms;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 短信发送类
 *
 * @author zhanggk
 */
@Slf4j
@Component
public class Sender {

    /**
     * 登陆短信模板ID
     */
    public static String LOGIN_CODE = "20100001";

    /**
     * 短信接收成功
     */
    private static String MSG_RETURN_CODE_SUCCESS = "000000";

    /**
     * 源号码(默认为10658830, 手机终端收到消息后显示的号码), 对于有扩展子号码的需求开放
     */
    private static String SOURCE_ADDR = "10658830";

    /**
     * 是否发送短信，0-不发送，1-发送
     */
    private static boolean isOpen;

    @Value("${system.sms.open}")
    public void setIsOpen(boolean isOpen) {
        Sender.isOpen = isOpen;
    }

    /**
     * MD5加密
     *
     * @param str 加密前的字符串
     * @return 返回加密后的字符串
     */
    private static String getMD5String(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5".toUpperCase());
            byte[] digest = md.digest(str.getBytes());
            return bytesToString(digest);
        } catch (Exception e) {
            log.error("md5加密失败，错误原因：[{}]", e.getMessage());
        }
        return null;
    }

    /**
     * 转换成String
     *
     * @param data byte数组
     * @return 转换后的string
     */
    private static String bytesToString(byte[] data) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] temp = new char[data.length * 2];
        for (int i = 0; i < data.length; i++) {
            byte b = data[i];
            temp[(i * 2)] = hexDigits[(b >>> 4 & 0xF)];
            temp[(i * 2 + 1)] = hexDigits[(b & 0xF)];
        }
        return new String(temp).toUpperCase();
    }

    /**
     * 生成header 请求头（用于合法性验证）
     *
     * @return RequestHeader
     */
    private static RequestHeader getRequestHeader() {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(now);
        String msgId = "2010100" + date + "00000000";
        RequestHeader rh = new RequestHeader();
        rh.setMsgId(msgId);
        rh.setDeviceId("2010");
        rh.setDevicePwd(getMD5String(msgId + "123abc!@#"));
        rh.setAccessPlatformID("100");
        return rh;
    }

    /**
     * 通用短信接口
     *
     * @param msgCode 短信模板ID,由消息下发平台统一配置分配
     * @param tel 目的手机号码,数组，可填多个
     * @param tplVars 模板中变量值(如模板中没有变量，可以为空)
     */
    public static void sendSMS(String msgCode, String[] tel, String[] tplVars) {
        Response response;
        // 根据配置文件，判断是否发送短信
        log.info("短信模板[{}]，手机号码：{}，短信内容：{}", msgCode, tel, tplVars);
        if (isOpen) {
            try {
                response = new MessageSenderServiceLocator().getMessageSender().sendSmTplMessage(getRequestHeader(),
                    SOURCE_ADDR, tel, msgCode, tplVars);
                log.info("response info:{}", response.toString());
                log.info("发送短信结果返回：code[{}], message[{}]", response.getReturnCode(), response.getDescription());
            } catch (Exception e) {
                log.error("短信发送失败，error[{}]", e);
            }
        }
    }
}
